<?php

class Admin_CategoriesController extends Zend_Controller_Action
{

    public function init()
    {
        require_once(APPLICATION_PATH . '/modules/admin/models/DbMapper/Categories.php');
        require_once(APPLICATION_PATH . '/modules/admin/models/DbTable/Categories.php');
    }

    protected function  prepareData($data)
    {
        $data['is_visible'] = (int) intval($data['is_visible']);
        $data['name'] = strip_tags($data['name']);

        return $data;
    }

    public function addAction()
    {
       if($this->_request->isPost()) {
           $categoriesDbMapper = new Admin_Model_DbMapper_Categories();
           $data = $this->_request->getPost();
           $data = $this->prepareData($data);

           if(!isset($data['name']) || !$data['name']) {
              $this->view->errorMessage = 'Название категории не указано!';
           } else {
               $this->view->isInsert = $categoriesDbMapper->insert($data);
           }

       }
    }

    public function indexAction() {
        $this->forward('list');
    }

    public function listAction()
    {
        $categoriesDbMapper = new Admin_Model_DbMapper_Categories();
        $this->view->categories = $categoriesDbMapper->fetchAll();
    }

    public function editAction()
    {
        $categoryDbMapper = new Admin_Model_DbMapper_Categories();
        $id = $this->getParam('id', null);

        if($this->_request->isPost()) {
            $data = $this->_request->getPost();
            $data = $this->prepareData($data);

            $this->view->isEdit = $categoryDbMapper->updateById($data, $id);
            $this->forward('list');
        } else {

            if($id) { $this->view->category = $categoryDbMapper->selectById($id); }

        }
    }

    public function deleteAction()
    {

    }

}
?>
